package com.jinzhi.jzapi.certificate.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jinzhi.api.pojo.vo.TokenVO;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.type.EnumErrorCode;
import com.jinzhi.common.utils.EhCacheUtil;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.UUIDUtils;
import com.jinzhi.jzapi.utils.HttpUtil;
import com.jinzhi.jzweb.domain.ConsultationsDO;
import com.jinzhi.jzweb.domain.MsgDO;
import com.jinzhi.jzweb.service.ConsultationsService;
import com.jinzhi.jzweb.service.MsgService;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Controller
@AllArgsConstructor
@RequestMapping("/jzApi/wximgCode")

public class WxApiImgCodeController extends BaseController {
    @Autowired
    private ConsultationsService consultationsService;
    @Autowired
    private UserService userService;
    @Autowired
    private MsgService msgService;

    /**
     * 获取微信登陆二维码地址
     * @return
     */
    @RequestMapping(value = "/wxlogCode",method = RequestMethod.GET)
    public String wxlogCode(HttpServletRequest request, Model model) {
        Map<String, String[]> params = request.getParameterMap();//针对get获取get参数
        String[] codes = params.get("code");//拿到的code的值
        String code = codes[0];//code
//这一步就是拼写微信api请求地址并 通过微信的appid 和 微信公众号的AppSecret 以及我们获取到的针对用户授权回调的code 拿到 这个用户的 openid和access_token
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=APPSECRET&code=CODE&grant_type=authorization_code".replace("APPID", "wxa5b743d1daed59cc").replace("APPSECRET", "11e991bed92333a7e433f626ad2a0d92").replace("CODE", code);
        System.out.println("requtl="+requestUrl);
        String requestResult = HttpUtil.sendGet(requestUrl);//我们需要自己写或者在网上找一个 doGet 方法 发送doGet请求
        JSONObject getCodeResultJson = JSON.parseObject(requestResult);//把请求成功后的结果转换成JSON对象
//        if(getCodeResultJson == null || getCodeResultJson.getString("openid") == null) {
//            try {
//                throw new Exception("没有匹配到信息");
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
        String wxcode=getCodeResultJson.get("openid").toString();

        UserDO userDOs= userService.getuserWx(wxcode);
        if(userDOs==null){
            //注册须知
            Wrapper<ConsultationsDO> consultationsDOWrapper = new EntityWrapper<ConsultationsDO>().orderBy("creater_date", false);
            consultationsDOWrapper.eq("first_column", "证书考试门户");
            consultationsDOWrapper.eq("state", 1);
            consultationsDOWrapper.eq("second_column", "注册须知").last("limit 1"); //只查询1条
            List<ConsultationsDO> consultationsDOList = consultationsService.selectList(consultationsDOWrapper);
            model.addAttribute("consultations", consultationsDOList);
            model.addAttribute("wxcode", wxcode);
            return  "certificateWeb/userWxCode";
        }else {
            try {
                //根据手机号码生成自定义登录态
                TokenVO returnToken = userService.getToken(userDOs.getMobile());

                //将生成的登录态和手机号码关联，并存到缓存中
                Map cache = new HashMap();
                cache.put("mobile", userDOs.getMobile());
                EhCacheUtil.put(returnToken.getToken(), cache);
                //返回登录态和用户信息
                Map<String, Object> map = new HashMap<>();
                map.put("token", returnToken.getToken());
                map.put("userName", userDOs.getUsername());
                map.put("type", userDOs.getType());
                map.put("uName", userDOs.getName());
                List<MsgDO> msg = msgService.findByKv("state", 0, "userId", userDOs.getId(), "type", 0);
                List<MsgDO> msg1 = msgService.findByKv("state", 0, "userId", userDOs.getId(), "type", 1);
                map.put("unreadNum0", msg.size());
                map.put("unreadNum1", msg1.size());
                request.getSession().setAttribute("userName", userDOs.getUsername());
               // return Result.ok(map);

                model.addAttribute("wxcode", wxcode);
                model.addAttribute("token", returnToken.getToken());
                model.addAttribute("userName", userDOs.getUsername());
                model.addAttribute("unreadNum0", msg.size());
                model.addAttribute("unreadNum1", msg1.size());

               // model.addAttribute("consultations", consultationsDOList);
                return  "certificateWeb/homepage/homepage2";
            } catch (AuthenticationException e) {
               // return Result.build(EnumErrorCode.userLoginFail.getCode(), EnumErrorCode.userLoginFail.getMsg());
            }


        }
        return  "certificateWeb/registerMobileWeb";
    }


    /**
     * 获取微信登陆二维码地址
     * @return
     */
    @RequestMapping(value = "/wxlogCodePx",method = RequestMethod.GET)
    public String wxlogCodePx(HttpServletRequest request, Model model) {
        Map<String, String[]> params = request.getParameterMap();//针对get获取get参数
        String[] codes = params.get("code");//拿到的code的值
        String code = codes[0];//code
//这一步就是拼写微信api请求地址并 通过微信的appid 和 微信公众号的AppSecret 以及我们获取到的针对用户授权回调的code 拿到 这个用户的 openid和access_token
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=APPSECRET&code=CODE&grant_type=authorization_code".replace("APPID", "wxa5b743d1daed59cc").replace("APPSECRET", "11e991bed92333a7e433f626ad2a0d92").replace("CODE", code);
        System.out.println("requtl="+requestUrl);
        String requestResult = HttpUtil.sendGet(requestUrl);//我们需要自己写或者在网上找一个 doGet 方法 发送doGet请求
        JSONObject getCodeResultJson = JSON.parseObject(requestResult);//把请求成功后的结果转换成JSON对象
//        if(getCodeResultJson == null || getCodeResultJson.getString("openid") == null) {
//            try {
//                throw new Exception("没有匹配到信息");
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
        String wxcode=getCodeResultJson.get("openid").toString();

        UserDO userDOs= userService.getuserWx(wxcode);
        if(userDOs==null){
            //注册须知
            Wrapper<ConsultationsDO> consultationsDOWrapper = new EntityWrapper<ConsultationsDO>().orderBy("creater_date", false);
            consultationsDOWrapper.eq("first_column", "证书考试门户");
            consultationsDOWrapper.eq("state", 1);
            consultationsDOWrapper.eq("second_column", "注册须知").last("limit 1"); //只查询1条
            List<ConsultationsDO> consultationsDOList = consultationsService.selectList(consultationsDOWrapper);
            model.addAttribute("consultations", consultationsDOList);
            model.addAttribute("wxcode", wxcode);
            return  "cultivateWeb/forgetPassPx";
        }else {
            try {
                //根据手机号码生成自定义登录态
                TokenVO returnToken = userService.getToken(userDOs.getMobile());

                //将生成的登录态和手机号码关联，并存到缓存中
                Map cache = new HashMap();
                cache.put("mobile", userDOs.getMobile());
                EhCacheUtil.put(returnToken.getToken(), cache);
                //返回登录态和用户信息
                Map<String, Object> map = new HashMap<>();
                map.put("token", returnToken.getToken());
                map.put("userName", userDOs.getUsername());
                map.put("type", userDOs.getType());
                map.put("uName", userDOs.getName());
                List<MsgDO> msg = msgService.findByKv("state", 0, "userId", userDOs.getId(), "type", 0);
                List<MsgDO> msg1 = msgService.findByKv("state", 0, "userId", userDOs.getId(), "type", 1);
                map.put("unreadNum0", msg.size());
                map.put("unreadNum1", msg1.size());
                request.getSession().setAttribute("userName", userDOs.getUsername());
                // return Result.ok(map);

                model.addAttribute("wxcode", wxcode);
                model.addAttribute("token", returnToken.getToken());
                model.addAttribute("userName", userDOs.getUsername());
                model.addAttribute("unreadNum0", msg.size());
                model.addAttribute("unreadNum1", msg1.size());

                return  "cultivateWeb/indexVxcode";
            } catch (AuthenticationException e) {
                // return Result.build(EnumErrorCode.userLoginFail.getCode(), EnumErrorCode.userLoginFail.getMsg());
            }


        }
        return  "certificateWeb/registerMobileWeb";
    }
    /**
     * 绑定手机号
     * @return
     */
    @Log("提交登录信息")
    @PostMapping(value = "/userAddWxCodeopenId")
    @ResponseBody
    Result<?> userAddWxCodeopenId(HttpServletRequest req, Model model,String wxcode,String mobile,String code) {
        System.out.println("hello=");
        String salt = UUIDUtils.get();
        //查询手机号是否注册
        Wrapper<UserDO> wrapper = new EntityWrapper();
        wrapper.eq("mobile", mobile);
        UserDO userDOs = userService.selectOne(wrapper);

        Object smsDemo = EhCacheUtil.get(mobile+"wx");

        if(smsDemo==null){
            return Result.build(EnumErrorCode.userLoginFai1l.getCode(), "验证码过期");
        }
        if(!smsDemo.equals(code)){
            return Result.build(EnumErrorCode.userLoginFai1l1.getCode(), "验证码不正确");
        }
        if(userDOs==null){
            return Result.build(EnumErrorCode.userLoginFai1l3.getCode(), EnumErrorCode.userLoginFai1l3.getMsg());
        }
        if(userDOs!=null){
            userDOs.setLoginWxCode(wxcode);
            userService.updateById(userDOs);
        }

        try {
//        UsernamePasswordToken token = new UsernamePasswordToken(userDOs.getUsername(), userDOs.getPassword());
//        //token.setRememberMe(false);//记住我是可选项，但只有会话缓存到redis等持久存储才能真正记住
//        Subject subject = SecurityUtils.getSubject();
//            subject.login(token);
            //将生成的登录态和手机号码关联，并存到缓存中
            //根据手机号码生成自定义登录态
            TokenVO returnToken = userService.getToken(userDOs.getMobile());
            Map cache = new HashMap();
            cache.put("mobile", userDOs.getMobile());
            EhCacheUtil.put(returnToken.getToken(), cache);
            //返回登录态和用户信息
            Map<String, Object> map = new HashMap<>();
            map.put("token", returnToken.getToken());
            map.put("userName", userDOs.getUsername());
            map.put("type", userDOs.getType());
            map.put("uName", userDOs.getName());
            List<MsgDO> msg = msgService.findByKv("state", 0, "userId", userDOs.getId(), "type", 0);
            List<MsgDO> msg1 = msgService.findByKv("state", 0, "userId", userDOs.getId(), "type", 1);
            map.put("unreadNum0", msg.size());
            map.put("unreadNum1", msg1.size());
            req.getSession().setAttribute("userName", userDOs.getUsername());
            return Result.ok(map);

       // return  "certificateWeb/homepage/wxCodehomepage";
        } catch (AuthenticationException e) {
            return Result.build(EnumErrorCode.userLoginFail.getCode(), EnumErrorCode.userLoginFail.getMsg());

        }
    }
    /**
     * 获取微信登陆二维码地址
     * @return
     */
    @GetMapping(value = "/userAddWxCode")
     String userAddWxCode(Model model) {
        //注册须知
        Wrapper<ConsultationsDO> consultationsDOWrapper = new EntityWrapper<ConsultationsDO>().orderBy("creater_date", false);
        consultationsDOWrapper.eq("first_column", "证书考试门户");
        consultationsDOWrapper.eq("state", 1);
        consultationsDOWrapper.eq("second_column", "注册须知").last("limit 1"); //只查询1条

        List<ConsultationsDO> consultationsDOList = consultationsService.selectList(consultationsDOWrapper);

        model.addAttribute("consultations", consultationsDOList);

        return  "certificateWeb/userWxCode";
    }

//    /**
//     * 获取微信登陆二维码地址
//     * @return
//     */
//    @RequestMapping(value = "/getQRCodeUrl",method = RequestMethod.POST)
//    public String getQRCodeUrl() {
//        String codeimg=null;
//
//        try {
//            String urlString = URLEncoder.encode("https://www.jz1x.com/jzApi/wximgCode/wxlogCode", "utf-8");
//
//            codeimg="https://open.weixin.qq.com/connect/qrconnect?appid=wxa5b743d1daed59cc&redirect_uri="+urlString+"&response_type=code&scope=snsapi_login&state=e97555458779708b99b9d40cb49f54245c7500e536445d32#wechat_redirect";
//
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        System.out.println("codeimg=="+codeimg);
//        Map map=new HashMap();
//        map.put("code",200);
//        map.put("url",codeimg);
//        map.put("msg","ok");
//
//        return  codeimg;
//    }



}
